<?php

namespace App\Http\Middleware\OpenShop;

use App\Service\OpenShop\User\RmsUserService;
use Closure;
use Illuminate\Http\Request;

class UserPermissionAuth
{
    const MODULE_OPEN_SHOP    = 'openShop';
    const MODULE_OPEN_SITE    = 'site';
    const MODULE_WORK_ORDER   = 'workOrder';
    const MODULE_CRUISE       = 'cruise';
    const MODULE_CRUISE_CHECK = 'cruiseCheck';
    const MODULE_CALLING_CARD = 'callingCards';
    const MODULE_PRODUCT_SELECTION_PROPOSAL = 'productSelectionProposal';// 选品建议

    /**
     * 校验用户是否有权限
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param string|null ...$guards
     * @return mixed
     */
    public function handle(Request $request, Closure $next, string $module = self::MODULE_OPEN_SHOP)
    {
        $action         = $request->route()->getAction('controller');
        $actionSplit    = explode('Controllers\\', $action);
        $controllerList = strtolower(str_replace(['@', '\\', 'Controller'], ['.', '.', ''], $actionSplit[1]));

        // 设置当前请求的uri
        $request->controllerUri = $controllerList;

        // 白名单
        $whiteList = (array)config('routeWhiteList.' . $module);
        if (in_array($controllerList, $whiteList)) {
            return $next($request);
        }

        // 获取所有需要校验的权限列表
        $permissionListAll = RmsUserService::getAllPermission($module);

        // 获取开店的权限列表
        $permissionList = getRmsUserPermissionList([], $module);

        //特殊权限控制  多个路由是一个权限控制
        $special = RmsUserService::permissionOutUp($controllerList, $permissionList);
        if (!$special) {
            return self::noAccess();
        }

        // 判断当前路由在不在 总路由中, 存在则校验,不存在则跳过
        if (in_array($controllerList, $permissionListAll)) {
            // 获取开店模块的权限列表
            if (empty($permissionList)) {
                return self::noAccess();
            }

            if (in_array($controllerList, $permissionList)) {
                return $next($request);
            } else {
                return self::noAccess();
            }
        } else {
            // 跳过校验
            return $next($request);
        }
    }

    public function noAccess()
    {
        return response()->json([
            'code' => 403,
            'msg'  => '没有对应权限',
        ]);
    }
}
